<?php

include_once APPLICATION_DIR . "/application/model/PRODUCT_IMAGE.php";

class Product_Image extends DataObjects_PRODUCT_IMAGE
{
	public static function validateInputFromProduct(&$product)
	{
		global $error_msg;

		$product_images = array();		
		$posted_multi_files = $_FILES["PRODUCT_IMAGE"];
		foreach($posted_multi_files['name'] as $i => $name) {
			$id = $_REQUEST['PRODUCT_IMAGE_ID'][$i];
			$product_image = new Product_Image();
			if ($id) {
				$product_image = $product->product_images[$id];
				$product_image->OLD_IMAGE = $product_image->IMAGE;
				if ($_REQUEST['PRODUCT_IMAGE_REMOVED'][$i]) {
					$product_image->REMOVED = 1;
					$product_images[] = $product_image;
					continue;
				}
			}
			$product_image->DISABLED = $_REQUEST['PRODUCT_IMAGE_DISABLED'][$i];

			$new_file = '';
			if ($name) {
				$posted_file = array(
					'name' => $posted_multi_files['name'][$i],
					'tmp_name' => $posted_multi_files['tmp_name'][$i]
				);

				$upload = new UPLOAD();
				$new_file = $upload->doUploadImage(PRODUCT_DIR."/image/", $posted_file, '', '190', '');
				if ($new_file) {
					$product_image->IMAGE = $new_file;
				} else {
					$error_msg->add('_MSG_UPLOAD_FAILED');
				}
			}
			if ($id || !empty($new_file)) {
				$product_images[] = $product_image;
			}
		}

		$product->product_images = $product_images;

        return $error_msg->isNoError();
	}

	public function update() {
		if (!empty($this->OLD_IMAGE) && $this->IMAGE != $this->OLD_IMAGE) {
			@unlink(PRODUCT_DIR."/image/{$this->OLD_IMAGE}");
			@unlink(PRODUCT_DIR."/image/thumb{$this->OLD_IMAGE}");
		}

		return parent::update();
	}
	
	public function delete() {
		if ($this->IMAGE) {
			@unlink(PRODUCT_DIR."/image/{$this->IMAGE}");
			@unlink(PRODUCT_DIR."/image/thumb{$this->IMAGE}");
		}

		return parent::delete();
	}

	public static function getList($id_product = 0) {
		$product_image = new Product_Image();
		if ($id_product) {
			$product_image->ID_PRODUCT = $id_product;
		}

		return $product_image->fetchListObject();
	}

	public static function getDir()
	{
		return PRODUCT_DIR.'/image';
	}
	
	public function getPath()
	{
		return self::getDir()."/{$this->IMAGE}";
	}
}
?>
